package medium;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by daodao on 2017/12/1.
 * Problem 5
 * Description: Given a string s, find the longest palindromic substring in s. You may assume that the maximum
 * length of s is 1000.
 *
 * Example 1: Input: "babad"
 *            Output: "bab"
 * Note: "aba" is also a valid answer.
 * Example 2: Input: "cbbd"
 *            Output: "bb"
 */
public class LongestPalindromicSubstring {
    static int maxLen = 0;
    static int startPos = 0;

    // 动态规划
    public static String longestPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        int len = s.length();
        int longestLen = 0;
        String result = null;
        int[][] dp = new int[len][len];
        for (int i = 0; i < s.length(); i++) {
            for (int j = 0; j < s.length() - i; j ++) {
                int k = j + i;
                if (s.charAt(j) == s.charAt(k) && (k - j <= 2 || dp[j + 1][k - 1] == 1)) {
                    dp[j][k] = 1;
                    if (k - j + 1 > longestLen) {
                        longestLen = k - j + 1;
                        result = s.substring(j, k + 1);
                    }
                }
            }
        }
        return result;
    }

    // Manacher算法
    public static String longestPalindrome2(String s) {
        if (s == null || s.length() < 2) {
            return s;
        }
        for (int i = 0; i < s.length(); i++) {
            extStrLen(i, i, s);// 子回文串长度为奇数
            extStrLen(i, i + 1, s);// 子回文串长度为偶数
        }
        return s.substring(startPos, startPos + maxLen);
    }
    private static void extStrLen(int i, int j, String s) {
        while (i >= 0 && j < s.length() && s.charAt(i) == s.charAt(j)) {
            i--;
            j++;
        }
        if (j - i - 1 > maxLen) {
            maxLen = j - i - 1;
            startPos = i + 1;
        }
    }
}
